# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.


from odoo import api, fields, models

import logging
_logger = logging.getLogger(__name__)

class Company(models.Model):
    _inherit = "res.company"

    company_inter_ids = fields.One2many('res.company.inter', 'company_id')

    @api.model
    def _find_company_from_partner(self, partner_id):
        company = self.sudo().search([('partner_id', '=', partner_id)],
                                     limit=1)
        return company or False

class CompanyInter(models.Model):
    _name = "res.company.inter"
    _description = "Company Inter"
    _rec_name = "inter_company_id"
    _order = "id"

    company_id = fields.Many2one('res.company', string='Company', 
        required=True, index=True, default=lambda self: self.env.user.company_id,
        help="Company related to this")

    inter_company_id = fields.Many2one('res.company', string='Inter Company', 
        required=True, index=True)
    
    """
    应该增加一个字段，设定对方的销售员是谁。
    """
    
    auto_po2so = fields.Boolean( default=False )
    

class PurchaseOrder(models.Model):
    _inherit = "purchase.order"
    
    @api.multi
    def button_confirm(self):
        """
        采购订单取消取消前，应先取消对应的销售订单。然后再取消采购订单。
        采购订单取消后，可以重置为草稿，这样。再次确认后，将再次生成销售订单。
        """
        
        res = super(PurchaseOrder, self).button_confirm()
        self._po2so()
        return res

    @api.multi
    def _po2so(self):
        
        so_sudo = self.env['sale.order'].sudo()
        
        for order in self:
            pass
            print(1234567890)
            
            dest_company = self.env['res.company']._find_company_from_partner(
                order.partner_id.id)

            if not dest_company:
                continue
            
            dest_company_inter = self.company_id.company_inter_ids.filtered(
                lambda item: item.inter_company_id.id == dest_company.id)
            
            if not dest_company_inter:
                continue
            
            if not dest_company_inter.auto_po2so:
                continue
            
            pass
            print(1234567890,'ok to so')
            
            vals = self._prepare_so( dest_company )
            
            so = so_sudo.create(vals)

            print(1234567890,so)
            
    
    def _prepare_so(self, dest_company):
        return {
            'origin': self.name,
            'partner_id': self.company_id.partner_id.id,
            'company_id': dest_company.id,
            'order_line': [(0,0,{
                'name': pol.name,
                'sequence': pol.sequence,
                'price_unit': pol.price_unit,
                #'tax_id': 
                'product_id': pol.product_id.id, 
                'product_uom': pol.product_uom.id,
                'product_uom_qty': pol.product_qty, 
            }) for pol in self.order_line ]
        }


""" 
class SaleOrder(models.Model):
    _inherit = "sale.order"

"""
